<template>
	<view class="login">
		<uni-icons type="contact-filled" class="icon" size="100" color="#adb0ad"></uni-icons>
		<button @click="getUserInfo">一键登录</button>
		<view class="beizhu">
			登录后尽享更多权益
		</view>
	</view>
</template>

<script>
	import {
		mapMutations
	} from 'vuex'
	export default {
		methods: {
			...mapMutations('m_user', ['saveUserInfo', 'updateToken']),
			// 获取登录接口需要的参数
			getUserInfo() {
				let _this = this
				uni.showModal({
					title: '微信授权登录',
					content: '获得你的公开信息（昵称、头像、地区及性别）',
					cancelText: '拒绝',
					confirmText: '允许',
					success(res) {
						if (res.confirm) {
							uni.getUserProfile({
								desc: '微信登录',
								success(r) {
									// console.log(r);
									_this.saveUserInfo(r.userInfo)
									_this.getToken(r)
								}
							})
						} else if (res.cancel) return uni.$showMsg('您取消了登录授权！')
					}
				})

			},
			// 获取登录接口需要的code参数
			async getToken(r) {
				const [err, res] = await uni.login().catch(err => err)
				if (err || res.errMsg !== "login:ok") return uni.$showMsg('登录失败！')
				// console.log(err);
				// console.log(res);
				// 准备参数对象
				const query = {
					code: res.code,
					encryptedData: r.encryptedData,
					iv: r.iv,
					rawData: r.rawData,
					signature: r.signature
				}
				// console.log(query);
				//换取token
				const {
					data: loginResult
				} = await uni.$http.post('/api/public/v1/users/wxlogin', query)
				console.log(loginResult);
				//这里无法成功调用后端登录接口，先写假数据
				if (loginResult.meta.status !== 400) return uni.$showMsg('登录失败！')
				let token =
					'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo'
				this.updateToken(token)
			}
		}
	}
</script>

<style lang="scss">
	.login {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 120px;

		.icon {
			border-radius: 50%;
			margin-bottom: 10px;
		}

		button {
			width: 650rpx;
			height: 100rpx;
			border-radius: 50rpx;
			background-color: #ac0003;
			margin-bottom: 20px;
			color: #fff;
		}

		.beizhu {
			color: #adb0ad;
			font-size: 12px;
		}
	}
</style>
